use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::product_relations::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub product_id: String,
    pub relation_id: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Product ID must not be empty."))]
    pub product_id: String,
    #[validate(length(min = 1, message = "Relation ID must not be empty."))]
    pub relation_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            product_id: self.product_id.as_ref().to_owned(),
            relation_id: self.relation_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::product_relations::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a product relation by the provided id
    ///
    /// # Errors
    ///
    /// When could not find product relation or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let product_relation = product_relations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(product_relations::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        product_relation.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds product relations by the provided product id
    ///
    /// # Errors
    ///
    /// When could not find product relations or DB query error
    pub async fn find_by_product_id(
        db: &DatabaseConnection,
        product_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let product_relations = product_relations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(product_relations::Column::ProductId, product_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(product_relations)
    }

    /// finds product relations by the provided relation id
    ///
    /// # Errors
    ///
    /// When could not find product relations or DB query error
    pub async fn find_by_relation_id(
        db: &DatabaseConnection,
        relation_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let product_relations = product_relations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(product_relations::Column::RelationId, relation_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(product_relations)
    }

    /// Asynchronously creates a product relation and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the product relation into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let product_relation = product_relations::ActiveModel {
            product_id: ActiveValue::set(params.product_id.to_string()),
            relation_id: ActiveValue::set(params.relation_id.to_string()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(product_relation)
    }

    /// Deletes the product relation
    ///
    /// # Errors
    ///
    /// When could not delete the product relation from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: product_relations::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the product relation's relation id
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_relation_id(
        mut self,
        db: &DatabaseConnection,
        relation_id: String,
    ) -> ModelResult<Model> {
        self.relation_id = ActiveValue::set(relation_id);
        Ok(self.update(db).await?)
    }
}
